const {BrowserWindow, ipcMain, dialog} = require('electron');
const os = require('os');
const path = require('path');
const fs = require('fs');
const db = require('../service/db');

function registerQUESIpc() {

    // 根据id获取考题列表
    ipcMain.handle('ques:getSelected', async (event, {ids}) => {
        return await db.getQuesListByIds(ids);
    });

    // 导出pdf
    ipcMain.handle('ques:generatePdf', async (event, {ids, answers}) => {
        console.log(answers);
        const win = BrowserWindow.getFocusedWindow(); // 当前窗口
        if (!win) return {status: 'error', message: '窗口未激活'};

        try {
            // 打开保存对话框
            const timestamp = Date.now(); // 获取当前毫秒级时间戳
            const filename = `${timestamp}.pdf`;
            const {filePath, canceled} = await dialog.showSaveDialog(win, {
                title: '导出PDF',
                defaultPath: path.join(os.homedir(), 'Desktop', filename),
                filters: [{name: 'PDF 文件', extensions: ['pdf']}]
            });

            if (canceled || !filePath) {
                // 用户取消
                return {status: 'cancelled'};
            }

            // 取出文件名（不含路径和类型）
            const nameWithoutExt = path.basename(filePath, path.extname(filePath));

            // 生成 PDF buffer
            const pdfData = await win.webContents.printToPDF({
                landscape: false,
                printBackground: true,
                pageSize: 'A4',
            });

            // 写入文件
            fs.writeFileSync(filePath, pdfData);

            // 打印记录入库
            console.log("用户保存为文件名：", nameWithoutExt);
            db.insertIntoHistory(ids, nameWithoutExt, answers).then(res => {
                console.log('插入成功，id:', res.id);
            }).catch(err => {
                console.error('插入失败:', err);
            });
            db.updateHistoryCount(ids).then(res => {
                console.log('修改成功:', ids);
            }).catch(err => {
                console.error('修改失败:', err);
            })

            return {status: 'success'};
        } catch (err) {
            console.error('PDF导出失败：', err);
            return {status: 'error', message: err.message};
        }
    });
}

module.exports = registerQUESIpc;